package com.um.jdy.app.activity.manager;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONUtil;
import com.um.jdy.app.activity.entity.dto.CouponsStationListQuery;
import com.um.jdy.app.activity.entity.vo.CouponsStationItemVO;
import com.um.jdy.app.device.entity.vo.StationItemVO;
import com.um.jdy.common.activity.code.CouponsCode;
import com.um.jdy.common.activity.entity.po.Coupons;
import com.um.jdy.common.activity.entity.po.CouponsStation;
import com.um.jdy.common.activity.entity.vo.CouponsAndStationVO;
import com.um.jdy.common.activity.entity.vo.DiscountsAndStationVO;
import com.um.jdy.common.activity.enums.ActivityEnum;
import com.um.jdy.common.activity.service.CouponsService;
import com.um.jdy.common.activity.service.CouponsStationService;
import com.um.jdy.common.activity.service.DiscountsStationService;
import com.um.jdy.common.device.enums.DeviceEnum;
import com.um.jdy.common.device.service.StationService;
import com.um.jdy.common.member.service.MemberUserService;
import com.um.springboot.starter.config.SystemSQL;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理类：优惠券站场关联表
 */
@Component
public class CouponsStationManager {

    @Autowired
    protected MemberUserService userService;

    @Autowired
    protected CouponsService couponsService;

    @Autowired
    protected StationService stationService;

    @Autowired
    protected CouponsStationService couponsStationService;

    @Autowired
    protected DiscountsStationService discountsStationService;

    @Autowired
    protected HttpServletRequest request;

    public Page<CouponsStationItemVO> getAvailableStations(CouponsStationListQuery query){
        Page<CouponsStationItemVO> page = new Page(query);

        Coupons couponsEntity = couponsService.getEntity(query.getActivity_coupons_id());
        if(null == couponsEntity){
            throw new ServiceException(CouponsCode.CouponsNotExist);
        }

        DeviceEnum.Type deviceType = query.getDevice_type();

        if(ActivityEnum.UseRange.Part.name().equals(couponsEntity.getAvailableDevice()) &&
                !JSONUtil.parseArray(couponsEntity.getDeviceTypes()).contains(deviceType.name())){
            return page;
        }

        StringBuffer conditionSql = new StringBuffer(" and 1 = 1 ");
        List conditionParams = ListUtil.toList(query.getLongitude(), query.getLatitude(), deviceType.name());

        if(ActivityEnum.UseRange.Part.name().equals(couponsEntity.getAvailable())){
            List<CouponsStation> couponsStationList = couponsStationService.getList("activity_coupons_id", query.getActivity_coupons_id());
            List<String> stationIdList = couponsStationList.stream()
                    .map(item -> item.getDeviceStationId()).collect(Collectors.toList());

            conditionSql.append(" and ? like concat('%', s.device_station_id, '%') ");
            conditionParams.add(CollUtil.join(stationIdList, ","));
        }

        String pageSql = SystemSQL.getInstance().getSystemSQL(String.format("get_%s_station_page", deviceType.name().toLowerCase()))
                .replace("[condition]", conditionSql.toString());
        String countSql = SystemSQL.getInstance().getSystemSQL(String.format("get_%s_station_count", deviceType.name().toLowerCase()))
                .replace("[condition]", conditionSql.toString());

        page = stationService.getViewModelPageBySql(page, pageSql, countSql, CouponsStationItemVO.class, conditionParams.toArray());

        List<CouponsAndStationVO> couponsList = couponsStationService.getAllCoupons(StpUtil.getLoginId(null));
        List<DiscountsAndStationVO> discountsList = discountsStationService.getAllDiscounts();

        page.getResult().forEach(item -> {
            item.setHasCoupons(couponsList.stream().anyMatch(coupons ->
                    ActivityEnum.UseRange.All.name().equals(coupons.getAvailable()) ||
                            coupons.getDeviceStationIdList().contains(item.getDeviceStationId())));
            item.setHasMoney(discountsList.stream().anyMatch(discounts ->
                    ActivityEnum.DiscountsType.Money.name().equals(discounts.getType()) &&
                            (ActivityEnum.UseRange.All.name().equals(discounts.getAvailableStation()) ||
                                    discounts.getDeviceStationIdList().contains(item.getDeviceStationId()))));
            item.setHasDiscount(discountsList.stream().anyMatch(discounts ->
                    ActivityEnum.DiscountsType.Discount.name().equals(discounts.getType()) &&
                            (ActivityEnum.UseRange.All.name().equals(discounts.getAvailableStation()) ||
                                    discounts.getDeviceStationIdList().contains(item.getDeviceStationId()))));
        });

        return page;
    }

}
